package org.ap.demo.api.config;

import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;

import com.fasterxml.jackson.databind.ObjectMapper;

public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {


    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException)
            throws  ServletException {
    	System.out.println("****************ai-demo-ocr AuthExceptionEntryPoint*************");
        Map<String,String> map = new LinkedHashMap<String, String>();
        String message = authException.getMessage();
        String description = authException.getMessage();
        map.put("error", "401");
        
        Throwable throwable = authException.getCause();
        if (throwable instanceof InvalidTokenException) {
        	map.put("error", "421");
			message = ((InvalidTokenException)throwable).getOAuth2ErrorCode();
			description = ((InvalidTokenException)throwable).getMessage();
		}
        
        map.put("message", message);
        map.put("description", description);
        map.put("path", request.getServletPath());
        map.put("timestamp", LocalDateTime.now().toString());
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(response.getOutputStream(), map);
        } catch (Exception e) {
            throw new ServletException();
        }
    }
}